package com.example.testapp.activity.ui.viewgroup;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.study.BlogDetailActivity;
import com.example.testapp.activity.adapter.HotsNewAdapter;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.BlogItem;
import com.example.testapp.activity.util.CircleImageView;
import com.example.testapp.activity.util.DateUtils;
import com.example.testapp.activity.view.ErrorHintView;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.squareup.picasso.Picasso;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 热门博客
 * Created by l on 2016/11/14.
 */

public class HotsBolgLayout extends RelativeLayout {
    private static final String TAG = "FreshBolgLayout";

    private Activity  mActivity;

    private boolean flag = false;
    private List<BlogItem> mList = new ArrayList<>();
    private HotsBolgAdapter mAdapter;
    private PullToRefreshListView  mListView;
    private ErrorHintView          mHintView;

    public static int VIEW_LIST = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;

    public HotsBolgLayout(Context context) {
        super(context);
        mActivity = (Activity) getContext();
        initView();
    }

    public HotsBolgLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mActivity = (Activity) getContext();
        initView();
    }

    public HotsBolgLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mActivity = (Activity) getContext();
        initView();
    }

    private void initView() {
        View view = View.inflate(getContext(), R.layout.layout_fresh_blog, this);
        mListView = (PullToRefreshListView) view.findViewById(R.id.fresh_blog_list);
        mHintView = (ErrorHintView) view.findViewById(R.id.hintView);
        setUpPullToList();
    }

    /**
     * 设置listview的下拉刷新
     */
    private void setUpPullToList() {
       mAdapter = new HotsBolgAdapter();
       mListView.setAdapter(mAdapter);
       mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
           @Override
           public void onRefresh(PullToRefreshBase<ListView> refreshView) {
               if (refreshView.isHeaderShown()){
                   flag = false;
                   loadHotsBolgInfo(true);
               }
           }
       });
       mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               BlogItem item = mList.get(position);
               Intent  intent = new Intent(mActivity, BlogDetailActivity.class);
               Bundle info = new Bundle();
               info.putSerializable("item", item);
               intent.putExtras(info);
               mActivity.startActivity(intent);
           }
       });
    }

    /**
     * 加载最新博客信息
     */
    public void loadHotsBolgInfo(final boolean clean) {
         showLoading(VIEW_LOADING);
        AsyncHttpUtil.get(Contacts.HOTS_PATH, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                mListView.onRefreshComplete();

                try {
                    showLoading(VIEW_LIST);
                    if (clean){
                        mList.clear();
                    }
                    ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                    parseFreshBolgXml(bis);
                    mAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                    showLoading(VIEW_LOADFAILURE);
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                showLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    /**
     * 解析最新博客
     * @param bis
     * @throws IOException
     * @throws XmlPullParserException
     */
    private void parseFreshBolgXml(InputStream bis) throws XmlPullParserException, IOException {
        XmlPullParser  parser = Xml.newPullParser();
        parser.setInput(bis, "UTF-8");
        int event = parser.getEventType();
        BlogItem item = null;

        while (event != XmlPullParser.END_DOCUMENT){
            switch (event){
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if ("entry".equals(parser.getName())){
                        flag = true;
                        item = new BlogItem();
                    }
                    if (flag){
                        if ("id".equals(parser.getName())){
                            String id = parser.nextText();
                            item.setId(id);
                        }else if ("title".equals(parser.getName())){
                            String title = parser.nextText();
                            item.setTitle(title);
                        }else if ("summary".equals(parser.getName())){
                            String summary = parser.nextText();
                            item.setSummary(summary);
                        }else if ("published".equals(parser.getName())){
                            String published = parser.nextText();
                            item.setPublished(published);
                        }else if ("updated".equals(parser.getName())){
                            String updated = parser.nextText();
                            item.setUpdated(updated);
                        }else if ("name".equals(parser.getName())){
                            String name = parser.nextText();
                            item.setName(name);
                        }else if ("uri".equals(parser.getName())){
                            String uri = parser.nextText();
                            item.setUri(uri);
                        }else if ("avatar".equals(parser.getName())){
                            String avatar = parser.nextText();
                            item.setAvatar(avatar);
                        }else if ("link".equals(parser.getName())){
                            String link = parser.nextText();
                            item.setHref(link);
                        }else if ("diggs".equals(parser.getName())){
                            String diggs = parser.nextText();
                            item.setDiggs(diggs);
                        }else if ("views".equals(parser.getName())){
                            String views = parser.nextText();
                            item.setViews(views);
                        }else if ("comments".equals(parser.getName())){
                            String comments = parser.nextText();
                            item.setComments(comments);
                        }
                    }
                    break;
                case XmlPullParser.TEXT:

                    break;
                case XmlPullParser.END_TAG:
                    if ("entry".equals(parser.getName())){
                        mList.add(item);
                    }
                    break;
            }
            event = parser.next();
        }
    }

    /**
     * 显示正在加载界面
     * @param i
     */
    private void showLoading(int i) {
        mListView.setVisibility(GONE);
        mHintView.setVisibility(GONE);

        switch (i){
            case 1:
                mHintView.hideLoading();
                mListView.setVisibility(VISIBLE);
                break;
            case 2:
                mHintView.hideLoading();
                mHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        loadHotsBolgInfo(true);
                    }
                });
                break;
            case 3:
                mHintView.hideLoading();
                mHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        loadHotsBolgInfo(true);
                    }
                });
                break;
            case 4:
                mHintView.loadingdata();
                break;
        }
    }

    public class HotsBolgAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null){
                convertView = View.inflate(mActivity, R.layout.view_item_fresh_bolg_lv, null);
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.uPic = (CircleImageView) convertView.findViewById(R.id.image);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.published = (TextView) convertView.findViewById(R.id.publish);
                holder.summary = (TextView) convertView.findViewById(R.id.summary);
                holder.viewsTv = (TextView) convertView.findViewById(R.id.views_tx);
                holder.diggsTv = (TextView) convertView.findViewById(R.id.diggs_tx);
                holder.commentsTv = (TextView) convertView.findViewById(R.id.comment_tx);
                holder.diggs = (LinearLayout) convertView.findViewById(R.id.hots_diggs);
                holder.views = (LinearLayout) convertView.findViewById(R.id.hots_views);
                holder.comment = (LinearLayout) convertView.findViewById(R.id.hots_comment);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            BlogItem item = mList.get(position);
            holder.title.setText(item.getTitle());
            holder.name.setText(item.getName());
            holder.summary.setText(item.getSummary());

            if (!TextUtils.isEmpty(item.getAvatar())){
                Picasso.with(mActivity).load(item.getAvatar()).placeholder(R.mipmap.touxiang).error(R.mipmap.touxing).into(holder.uPic);
            }
            if (!TextUtils.isEmpty(item.getPublished())){
                holder.published.setText(DateUtils.convertGMTToLoacale(item.getPublished()));
            }
            if (!TextUtils.isEmpty(item.getViews())){
                holder.viewsTv.setText(item.getViews());
            }else{
                holder.viewsTv.setText("");
            }

            if (!TextUtils.isEmpty(item.getComments())){
                holder.commentsTv.setText(item.getComments());
            }else{
                holder.commentsTv.setText("");
            }
            if (!TextUtils.isEmpty(item.getDiggs())){
                holder.diggsTv.setText(item.getDiggs());
            }else{
                holder.diggsTv.setText("");
            }
            return convertView;
        }

        class ViewHolder{
            TextView title;
            CircleImageView uPic;
            TextView summary;
            TextView published;
            TextView viewsTv;
            TextView diggsTv;
            TextView name;
            TextView commentsTv;
            TextView textViews;
            LinearLayout views;
            LinearLayout diggs;
            LinearLayout comment;
        }
    }
}
